import { Module } from "vuex";

import { IRootState } from "../types";
import { IPlayer } from "./type";

import { 
  getSongDetail
} from "@/service/player";
import { getRandomNumber } from "@/utils/math-utils";


const playerModule: Module<IPlayer, IRootState> = {
  namespaced: true,
  state() {
    return {
      currentSong: {},  //播放歌曲
      songIndex: 0,     //歌曲索引
      playList: [],     //歌曲列表
      sequence: 0       //播放顺序0/顺序 1/随机 2/单曲
    }
  },
  mutations: {
    changeCurrentSong(state, song) {
      state.currentSong = song
    },
    changeSongIndex(state, index) {
      state.songIndex = index
    },
    changePlayList(state, list) {
      state.playList = list
    },
    changeSequence(state, sequence) {
      state.sequence = sequence
    }
  },
  actions: {
    async getSongDetailAction({state, commit}, ids: number) {
      /**
        *  两种情况
        * 一、存在: 根据索引取出歌曲，纪录index。
        * 二、不存在：拿着ids请求，然后添加，纪录index。
      */
      const { playList } = state;
      const index = playList.findIndex(item => item.id === ids);
      let song = null;

      if (index !== -1) {
        song = playList[index];
        commit("changeSongIndex", index); 
      } else {
        const res = await getSongDetail(ids);
        song = res.songs && res.songs[0];
        if (!song) return;
        const newPlayList = [...playList];
        newPlayList.push(song);
        const indey =  newPlayList.length - 1;
        commit("changePlayList", newPlayList);
        commit("changeSongIndex", indey);
      }

      commit("changeCurrentSong", song);
    },
    changeSongIndexAndSongAction({state, commit}, tag: number) {
      let { playList, sequence, songIndex } = state;
      
      //0/顺序 1/随机 2/单曲   顺序和单曲的逻辑一样只在歌曲结束时判断，所以上/下一首判断随机，默认是顺序和单曲的逻辑。
      switch (sequence) {
        case 1:
            let randomIndex = getRandomNumber(playList.length);
            while (randomIndex === songIndex) {
              randomIndex = getRandomNumber(playList.length);
            }
            songIndex = randomIndex;
          break;
        default:
            songIndex += tag;
            if (songIndex >= playList.length) songIndex = 0;
            if (songIndex < 0) songIndex = playList.length - 1;
          break;
      }

      const song = playList[songIndex];
      commit("changeCurrentSong", song);
      commit("changeSongIndex", songIndex);
    }
  }
}

export default playerModule;